package vn.vfriends.id.bean;

import java.io.Serializable;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.id.jpa.entity.User;
import vn.vfriends.id.service.UserService;

/**
 *
 * @author tuan@vfriends.vn
 */
@Named
@ConversationScoped
public class ChangePassBean implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(ChangePassBean.class);
    
    private String oldPassword;
    
    private String password;
    
    private String reTypePassword;
    
    @Inject private UserService userService;
    
    @Inject private Conversation conversation;
    
    @Resource(lookup = "mail/noreply")
    private Session mailSession;
    
    @PostConstruct
    public void init() {
        if (conversation.isTransient()) {
            conversation.begin();
        }
    }

    public Conversation getConversation() {
        return conversation;
    }

    public String getOldPassword() {
        return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getReTypePassword() {
        return reTypePassword;
    }

    public void setReTypePassword(String reTypePassword) {
        this.reTypePassword = reTypePassword;
    }
    
    public void changeAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
            HttpSession session = request.getSession();
            User user = (User)session.getAttribute("LOGGED_USER");
            String digestOldPass = DigestUtils.md5Hex(this.oldPassword);
            if(!digestOldPass.equals(user.getPassword())) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Mật khẩu hiện tại không đúng", ""));
            } else if(!this.password.equals(this.reTypePassword)) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Nhập lại mật khẩu mới không khớp", ""));
            } else {
                user.setPassword(DigestUtils.md5Hex(password));
                this.userService.edit(user);
                //  Send new pass to the email
                String subject = "New password";
                String body = "Your new password is: " + this.password;
                this.sendEmail(user.getEmail(), subject, body);
                FacesContext.getCurrentInstance().getExternalContext().redirect("profile.jsf");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
    }
    
    private void sendEmail(String to, String subject, String body) throws Exception {
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress(mailSession.getProperty("mail.from")));
        InternetAddress[] address = {new InternetAddress(to)};
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
    }
}
